<?php
/**
 * @version SVN: $Id: languageconverter.php 1189 2010-05-07 10:59:02Z elkuku $
 * @package    EasyCreator
 * @subpackage Helpers
 * @author     EasyJoomla {@link http://www.easy-joomla.org Easy-Joomla.org}
 * @author     Nikolai Plath {@link http://www.nik-it.de}
 * @author     Created on 23-Apr-2010
 * @license    GNU/GPL, see JROOT/LICENSE.php
 */

//-- No direct access
defined('_JEXEC') or die('=;)');

/**
 *
 * Temporary class to convert language ini and php files
 * from Joomla! 1.5 to 1.6
 *
 */
class ECRLanguageConverter
{
    private $forbiddenKeys = array('null', 'yes', 'no', 'true', 'false', 'on', 'off', 'none');
    private $forbiddenChars = array('{', '}', '|', '&', '~', '!', '[', '(', ')', '^', '$');

    private $cleanRegEx = '';//"/JText::_\(\s*\'(.*)\'\s*\)|JText::_\(\s*\"(.*)\"\s*\)|JText::sprintf\(\s*\'(.*)\'[-,$>()\"':\sA-z0-9]+\)|JText::sprintf\(\s*\"(.*)\"[-,$>()\"'\sA-z0-9]+\)|JText::printf\(\s*\'(.*)\'[-,$>()\"'\sA-z0-9]+\)|JText::printf\(\s*\"(.*)\"[-,$>()\"'\sA-z0-9]+\)/iU";

    private $options = null;

    public $prefix = '';

    public function __construct($options)
    {
        $this->cleanRegEx = "/JText::_\(\s*\'(.*)\'\s*\)|JText::_\(\s*\"(.*)\"\s*\)".
		    "|JText::sprintf\(\s*\"(.*)\"|JText::sprintf\(\s*\'(.*)\'".
		    "|JText::printf\(\s*\'(.*)\'|JText::printf\(\s*\"(.*)\"/iU";

        if($options instanceof JObject)
        {
            $this->options = $options;;
        }
        else
        {
        	JError::raiseWarning(100, JText::_('Invalid options for lanuage converter'));

        	$this->options = new JObject();
        }
    }//function

    public static function getKnownLanguageTags()
    {
        $languages = JFactory::getLanguage()->getKnownLanguages();

        //--assure that default 'en-GB' is in first place
        $result = array('en-GB');

        foreach ($languages as $key => $language)
        {
            if($key != 'en-GB')
            {
                $result[] = $key;
            }
        }//foreach

        return $result;
    }//function

    public function isCleanKey($key)
    {
        return $key == $this->cleanKey($key);
    }//function

    public function cleanKey($key)
    {
        $key = trim($key);
        if($this->options->get('remove_bads'))
        {
            $key = str_replace($this->forbiddenChars, '', $key);
            $key = trim($key);
        }

        if($this->options->get('convert_white_space')) $key = str_replace(' ', '_', $key);

        if($this->options->get('convert_quotes')) $key = str_replace('"', '__QQ__', $key);

        if($this->options->get('convert_all_caps')) $key = strtoupper($key);

        if($this->options->get('add_prefix'))
        {
            if( ! $this->prefix) continue;

            if(strpos($key, $this->prefix) !== 0)
            {
                $key = $this->prefix.'_'.$key;
            }
        }

        if($this->options->get('convert_forbidden'))
        {
            if(in_array(strtolower($key), $this->forbiddenKeys))
            {
                //-- Forbidden key add an underscore
                $key = $key.'_';
            }
        }

        return $key;
    }//function

    public function cleanLangFileErrors($lines, $errors)
    {
        $i = 0;

        for($i = 0; $i < count($lines); $i++)
        {
            $parts = $this->splitLine($lines[$i]);

            if($parts[0] != '' && $parts[1] != '')
            {
                foreach($errors as $error)
                {
                    if(strtoupper($error) == strtoupper($parts[0]))
                    {
                        $parts[0] = $this->cleanKey($parts[0]);
                        $lines[$i] = $parts[0].'='.$parts[1];
                    }
                }//foreach
            }
        }//for

        return $lines;
    }//function

    public function cleanValue($value)
    {
        ;
    }//function

    public function findPHPErrors($code, $bads = array())
    {
        if( ! count($bads)) return array(); //good ?

        preg_match_all($this->cleanRegEx, $code, $matches, PREG_SET_ORDER );

        $errors = array();

        foreach($matches as $match)
        {
            foreach($match as $key=> $m)
            {
                $m = trim($m);
                if ($m == ''|| $key == 0) continue;

                $value = $m;
            }//foreach

            if($value)
            {
                if(in_array($value, $bads) || ! count($bads))//-count(bads)
                {
                    $errors[$value] = $match[0];
                }
            }
        }//foreach

        return $errors;
    }//function

    public function cleanLines($lines)
    {
        $newLines = array();

        foreach($lines as $line)
        {
            $line = trim($line);

            if($line == '')
            {
                //-- Blank
                $newLines[] = $line;
                continue;
            }

            if(strpos($line, '#') === 0)
            {
                //-- Old style comment
                $newLines[] = ';'.substr($line, 1);
            }
            elseif(strpos($line, ';') === 0)
            {
                //-- New style comment
                $newLines[] = $line;
            }
            else
            {
                $parts = explode('=', $line);

                if(count($parts) > 1)
                {
                    if(strpos($parts[1], '"') === 0)
                    {
                        //-- It's already quoted
                        $newLines[] = $line;
                    }
                    else
                    {
                        //-- Quote it..
                        $pos = strpos($line, '=');
                        $lastPart = substr($line, $pos + 1);
                        $lastPart = str_replace('"', '"__QQ__"', $lastPart);
                        $newLines[] = $parts[0].'="'.$lastPart.'"';
                    }
                }
                else
                {
                    //-- Just add it..
                    $newLines[] = $line;
                }
            }
        }//foreach

        return $newLines;
    }//function

    public function splitLine($line)
    {
        $pos = strpos($line, '=');
        $firstPart = substr($line, 0, $pos);
        $lastPart = substr($line, $pos + 1);

        return array($firstPart, $lastPart);
    }//function

    public function getDiffTable($origCode, $newCode, $showAll = true)
    {
        $codeOrig = explode("\n", htmlentities($origCode));
        $codeNew = explode("\n", htmlentities($newCode));
        ecrLoadHelper('DifferenceEngine');

        //--we are adding a blank line to the end.. this is somewhat 'required' by PHPdiff
        if($codeOrig[count($codeOrig)-1] != '')
        {
            $codeOrig[] = '';
        }

        if($codeNew[count($codeNew)-1] != '')
        {
            $codeNew[] = '';
        }

        $dwDiff = new Diff($codeOrig, $codeNew);
        $dwFormatter = new TableDiffFormatter();

        //-- Small hack to display the whole file - :|
        if($showAll)
        {
            $dwFormatter->leading_context_lines = 99999;
            $dwFormatter->trailing_context_lines = 99999;
        }

        return $dwFormatter->format($dwDiff);
    }//function

}//class
